﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using MenusHunter.Core.Utilities;

namespace MenusHunter.Core.Helper
{
    public class RestaurantsHelper
    {
        public static List<Restaurant> ListRestaurant()
        {
            using (var db = new MenusHunterDataContext())
            {
                return (db.Restaurants).ToList();
            }
        }

        public static Restaurant GetRestaurantById(int id)
        {
            using (var db = new MenusHunterDataContext())
            {
                return (from r in db.Restaurants where r.Id == id select r).SingleOrDefault();
            }
        }

        public static bool NewRetaurant(Restaurant restaurant)
        {
            using (var db = new MenusHunterDataContext())
            {
                db.Restaurants.InsertOnSubmit(restaurant);

                return restaurant.Id > 0;
            }
        }

        public static bool UpdateRestaurant(Restaurant restaurant)
        {
            using (var db = new MenusHunterDataContext())
            {
                db.Restaurants.InsertOnSubmit(restaurant);
                db.SubmitChanges();
                return true;
            }
        }

        public static bool DeleteRestaurant(Restaurant restaurant)
        {
            using (var db = new MenusHunterDataContext())
            {
                db.Restaurants.DeleteOnSubmit(restaurant);
                db.SubmitChanges();
                return true;
            }
        }

        public List<Restaurant> GetListRestaurantsAround(double currentLat, double currrentLong, double radius,
                                                         int offset, int limit)
        {
            using (var db = new MenusHunterDataContext())
            {
                var restaurants = db.Restaurants.OrderBy(t => t.Name).ToList();
                var rowNum = 0;
                var totalRow = 0;
                return
                    (from restaurant in
                         restaurants.Where(restaurant => rowNum++ >= offset).TakeWhile(restaurant => totalRow++ <= limit)
                     let dicstance =
                         Utils.CalcDistance2Point(currentLat, currrentLong, restaurant.Latitude, restaurant.Longtitude)
                     where dicstance < radius
                     select restaurant).ToList();
            }
        }
    }
}